package com.domainchen.framework.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.domainchen.framework.common.util.ArrayUtil;
import com.domainchen.framework.common.util.CodecUtil;
import com.domainchen.framework.common.util.StreamUtil;
import com.domainchen.framework.common.util.StringUtils;
import com.domainchen.framework.core.bean.FormParam;
import com.domainchen.framework.core.bean.Param;

/**
 * @author domainchen or cytxiamen@163.com
 * @version 创建时间：2016年3月15日 下午9:05:49
 * @类说明 请求助手类
 */
public final class RequestHolder {

	/**
	 * 创建请求参数  对象
	 * 
	 * @param request
	 * @return
	 */
	public static Param createParam(HttpServletRequest request) throws IOException {
		List<FormParam> formParamList = new ArrayList<FormParam>();
		formParamList.addAll(parseParameterNames(request));
		formParamList.addAll(parseInputStream(request));
		return new Param(formParamList);
	}

	/**
	 * 获取非Url上的参数
	 * @param request
	 * @return
	 */
	public static List<FormParam> parseParameterNames(HttpServletRequest request) {
		List<FormParam> formParamList = new ArrayList<FormParam>();
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String filedName = (String) paramNames.nextElement();
			String[] filedValues = request.getParameterValues(filedName);
			if (ArrayUtil.isNotEmpty(filedValues)) {
				Object filedValue = null;
				if (filedValues.length == 1) {
					filedValue = filedValues[0];
				} else {
					StringBuffer strBuffer = new StringBuffer();
					for (int i = 0; i < filedValues.length; i++) {
						strBuffer.append(filedValues[i]);
						if (i != filedValues.length - 1) {
							strBuffer.append(StringUtils.SEPARATOR);
						}
					}
					filedValue = strBuffer.toString();
				}
				formParamList.add(new FormParam(filedName, filedValue));
			}
		}
		return formParamList;
	}

	/**
	 * 获取URL 上的参数
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static List<FormParam> parseInputStream(HttpServletRequest request) throws IOException {
		List<FormParam> formParamList = new ArrayList<FormParam>();
		String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
		if (StringUtils.isNotEmpty(body)) {
			String[] params = body.split("&");
			// StringUtils.splitString(body,// "&");
			if (ArrayUtil.isNotEmpty(params)) {
				for (String param : params) {
					String[] array = param.split("=");// StringUtils.splitString(param,//
														// "=");
					if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
						String paramName = array[0];
						String paramValue = array[1];
						formParamList.add(new FormParam(paramName, paramValue));
					}
				}
			}
		}
		return formParamList;
	}

}
